package c03.thread.api.interrupt;

import lombok.extern.slf4j.Slf4j;

/**
 * 打断正常运行的线程
 */
@Slf4j(topic = "c.InterruptRunningThread")
public class InterruptRunningThread {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            log.debug("线程t初始打断状态: {}", Thread.currentThread().isInterrupted()); // true
            while (true) {
                Thread current = Thread.currentThread();
                boolean interrupted = current.isInterrupted();
                if (interrupted) {
                    log.debug("interrupted by thread main");
                    break;
                }
            }
        }, "t");
        t.start();

        Thread.sleep(1000);
        t.interrupt(); // t处于RUNNABLE状态，设置打断标记
        /*
        1. 如果被打断线程正在 sleep,wait,join 会导致被打断的线程抛出 InterruptedException，并清除打断标记 ;
        2. 如果打断的正在运行的线程,则会设置 打断标记 ;
        3. park 的线程被打断,也会设置 打断标记
         */
        log.debug("执行t.interrupt()后，线程t打断状态: {}", t.isInterrupted()); // true
    }

}
